package com.ias.agdis_r.activity.message;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

import com.android.volley.NoConnectionError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.ias.agdis_r.R;
import com.ias.agdis_r.activity.BaseKeyListActivity;
import com.ias.agdis_r.activity.MainActivity;
import com.ias.agdis_r.bean.message.MessageTemplate;
import com.ias.agdis_r.db.MyBeanTempDBHelper;
import com.ias.agdis_r.db.message.MyMessageBean;
import com.ias.agdis_r.manager.DataBaseManager;
import com.ias.agdis_r.manager.DataManager;
import com.ias.agdis_r.manager.EffectManager;
import com.ias.agdis_r.manager.JavaBeanManager;
import com.ias.agdis_r.module.MessageModel;
import com.ias.agdis_r.module.RestfulUri;
import com.ias.agdis_r.terminalmanager.restful.base.endpoint.response.BaseResponseHeader;
import com.ias.agdis_r.terminalmanager.restful.message.endpoint.request.WorkingMsgUpRequest;
import com.ias.agdis_r.terminalmanager.restful.message.endpoint.response.WorkingMsgUpResponse;
import com.ias.agdis_r.util.S;
import com.ias.agdis_r.util.SecurityUtil;
import com.ias.agdis_r.view.MyProgressBar;
import com.ias.agdis_r.volley.GsonRequest;
import com.ias.agdis_r.volley.callback.BaseOnVolleyErrorAdapter;
import com.ias.agdis_r.volley.callback.BaseOnVolleyErrorListener;
import com.ias.agdis_r.volley.callback.BaseOnVolleySuccessListener;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * 短语发送页：实现发送短语类型：普通短语，任务短语，催办短语，短语回复。
 * 启动时Intent需要携带参数，EXTRA_TYPE为必选参数，指示不同的短语类型，取值：TYPE_NORMAL,TYPE_REMIND,
 * TYPE_TASK;不传是默认为普通短语；可选参数见各TYPE开头常量注释，不同类型短语需要传入相应参数方可正常工作。
 *
 * @author qibo.yu
 * @version 2015年8月17日 下午2:36:03
 **/
public class MessageSendActivity extends BaseKeyListActivity implements AdapterView.OnItemClickListener, View.OnClickListener {

    /**
     * 普通短语，不需要传参数
     */
    public static final String TYPE_NORMAL = "com.ias.agdis_r.type.TYPE_NORMAL";
    /**
     * HTT催办短语，需要传EXTRA：TNB,FKE,RDN,PID
     */
    public static final String TYPE_REMIND = "com.ias.agdis_r.type.TYPE_REMIND";
    /**
     * 任务短语，EXTRA：TNB,FKE,AOD
     */
    public static final String TYPE_TASK = "com.ias.agdis_r.type.TYPE_TASK";

    public static final String EXTRA_TYPE = "com.ias.agdis_r.activity.ext_type";

    public static final String EXTRA_TNB = "com.ias.agdis_r.activity.ext_tnb";
    public static final String EXTRA_FKE = "com.ias.agdis_r.activity.ext_fke";
    public static final String EXTRA_FLN = "com.ias.agdis_r.activity.ext_fln";
    public static final String EXTRA_AOD = "com.ias.agdis_r.activity.ext_aod";
    /**
     * 针对回复消息时，传入待回复消息ID
     */
    public static final String EXTRA_TGN = "com.ias.agdis_r.activity.ext_tgn";
    /**
     * 针对回复消息时，传入待回复消息内容，协议要求
     */
    public static final String EXTRA_TXT = "com.ias.agdis_r.activity.ext_txt";
    public static final String EXTRA_RDN = "com.ias.agdis_r.activity.ext_rdn";
    /**
     * 任务监控项进程代码
     */
    public static final String EXTRA_PID = "com.ias.agdis_r.activity.ext_pid";

    /**
     * TYPE
     */
    private String extra_type;
    private String extra_tnb;
    private String extra_fke;
    private String extra_fln;
    private String extra_aod;
    private String extra_tgn;
    private String extra_txt;
    private String extra_rdn;
    private String extra_pid;

    private MyBeanTempDBHelper<MessageTemplate> beanTempDBHelper;
    private MyBeanTempDBHelper<MyMessageBean> myMessageDBHelper;
    private SimpleCursorAdapter adapter;

    private SQLiteDatabase sqLiteDatabase;
    private Cursor cursor;

    /**
     * 缓存当前要发送的消息
     */
    private MyMessageBean messageBean;

    private EditText editText;
    private Button btnSend;
    private MyProgressBar progressBar;

    private TextView title;

    private String selectedTemplateId;

    private RequestQueue requestQueue;

    private BaseOnVolleySuccessListener<WorkingMsgUpResponse> successListener = new BaseOnVolleySuccessListener<WorkingMsgUpResponse>() {
        @Override
        public void onRequestSuccess(WorkingMsgUpResponse response) {
            saveMessageTosqlite(messageBean);
            progressBar.setVisibility(View.GONE);
            EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE, getString(R.string.sendSucceed), false);
            //如果发送成功，清空输入框
            if(editText!=null){
                editText.setText("");
            }
        }

        @Override
        public void onRequestFailed(BaseResponseHeader header) {
            EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE, getString(R.string.serviceError), false);
            progressBar.setVisibility(View.GONE);
        }
    };

    private BaseOnVolleyErrorListener errorListener = new BaseOnVolleyErrorAdapter() {
        @Override
        public void onErrorOccurred(VolleyError e) {
            String msg = getString(R.string.error);
            if (e instanceof TimeoutError) {

                msg = DataBaseManager.getInstance().getContext().getString(R.string.request_err_timeout);
            } else if (e instanceof ServerError) {
                //显示接收消息异常
                msg = DataBaseManager.getInstance().getContext().getString(R.string.request_err_servererror);
            } else if (e instanceof NoConnectionError) {
                msg = DataBaseManager.getInstance().getContext().getString(R.string.request_err_noconnection);
            }
            EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE, msg, false);
            progressBar.setVisibility(View.GONE);
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getExtras();
        super.onCreate(savedInstanceState);
        this.requestQueue = Volley.newRequestQueue(this);

        setContentView(R.layout.activity_message_send);
        initactionBar();
        setTitle(R.string.MessageSendActivity);

        editText = (EditText) findViewById(R.id.edit_message);
        btnSend = (Button) findViewById(R.id.btn_send);
        btnSend.setOnClickListener(this);

        progressBar = (MyProgressBar) findViewById(R.id.progressBar);
        progressBar.setOnVisibilityChangeListener(new MyProgressBar.OnVisibilityChangeListener() {

            @Override
            public void onVisibilityChanged(boolean visibity) {
                if (visibity) {
                    btnSend.setVisibility(View.GONE);
                } else {
                    btnSend.setVisibility(View.VISIBLE);
                }

            }

        });

        beanTempDBHelper = new MyBeanTempDBHelper<MessageTemplate>(this, MessageTemplate.class);
        myMessageDBHelper = new MyBeanTempDBHelper<MyMessageBean>(this, MyMessageBean.class);
        sqLiteDatabase = beanTempDBHelper.getReadableDatabase();

        getListView().setOnItemClickListener(this);

        // 如果模板未加载，加载之
        if (JavaBeanManager.getInstance().getMSGShort().size() == 0
                && JavaBeanManager.getInstance().getMSGRemind().size() == 0) {
            loadTemplate();
        } else {
            bindData(extra_type);
        }

    }

    @Override
    protected void onDestroy() {
        sqLiteDatabase.close();
        sqLiteDatabase = null;
        super.onDestroy();
        if(null != requestQueue)
        requestQueue.stop();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (cursor.moveToPosition(position)) {
            if (cursor.moveToPosition(position)) {
                editText.setText(cursor.getString(1));
                selectedTemplateId = cursor.getString(0);
            }

        }
    }

    private void getExtras() {
        Intent intent = getIntent();

        for (String key : intent.getExtras().keySet()) {
            Log.i("C_ext", key + ":" + intent.getStringExtra(key));
        }

        this.extra_type = intent.getStringExtra(EXTRA_TYPE);
        this.extra_tnb = intent.getStringExtra(EXTRA_TNB);
        this.extra_fke = intent.getStringExtra(EXTRA_FKE);
        this.extra_fln = intent.getStringExtra(EXTRA_FLN);
        this.extra_aod = intent.getStringExtra(EXTRA_AOD);
        this.extra_tgn = intent.getStringExtra(EXTRA_TGN);
        this.extra_txt = intent.getStringExtra(EXTRA_TXT);
        this.extra_rdn = intent.getStringExtra(EXTRA_RDN);
        this.extra_pid = intent.getStringExtra(EXTRA_PID);

        if (S.isEmpty(extra_type)) {
            extra_type = TYPE_NORMAL;
            Log.d("C_EXTRA", "未传入类型参数，使用默认值 -> TYPE_NORMAL");
        }
        switch (extra_type) {
            case TYPE_REMIND:
                if (S.isEmpty(extra_tnb) || S.isEmpty(extra_fke) || S.isEmpty(extra_rdn) || S.isEmpty(extra_pid)) {
                    Log.w("C_EXTRA", "TYPE_REMIND -> TNB,FKE,RDN,PID须同时传入");
                    Log.w("C_EXTRA", "extra extra_tnb's value is " + extra_tnb);
                    Log.w("C_EXTRA", "extra extra_fke's value is " + extra_fke);
                    Log.w("C_EXTRA", "extra extra_rdn's value is " + extra_rdn);
                    Log.w("C_EXTRA", "extra extra_pid's value is " + extra_pid);
                }
                break;
            case TYPE_TASK:
                if (S.isEmpty(extra_tnb) || S.isEmpty(extra_fke) || S.isEmpty(extra_aod)) {
                    Log.w("C_EXTRA", "TYPE_TASK -> TNB,FKE,AOD须同时传入");
                    Log.w("C_EXTRA", "extra extra_tnb's value is " + extra_tnb);
                    Log.w("C_EXTRA", "extra extra_fke's value is " + extra_fke);
                    Log.w("C_EXTRA", "extra extra_aod's value is " + extra_aod);
                }
                break;
        }

    }

    private Cursor getDataByType(String type) {
        StringBuilder sqlBuilder = new StringBuilder("SELECT _id, txt FROM ").append(beanTempDBHelper.getTableName())
                .append(" ");
        switch (type) {
            case TYPE_NORMAL:
                sqlBuilder.append("WHERE flag = 'N'");
                break;
            case TYPE_TASK:
                sqlBuilder.append("WHERE flag = 'F' and aod = '").append(extra_aod).append("'");
                break;
            case TYPE_REMIND:
                sqlBuilder.append("WHERE flag = 'R' AND pid = '");
                String pid = getIntent().getStringExtra(EXTRA_PID);
                sqlBuilder.append(pid).append("'");
                String rtp = getIntent().getStringExtra(MessageModel.RTP);
                sqlBuilder.append(" and (senm = '' or senm is null or senm = '").append(rtp).append("')");
                break;
        }

        return beanTempDBHelper.getReadableDatabase().rawQuery(sqlBuilder.toString(), null);
    }

    private void bindData(String type) {
        cursor = getDataByType(type);
        adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_single_choice, cursor,
                new String[]{"txt"}, new int[]{android.R.id.text1},
                SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);

        setListAdapter(adapter);
        adapter.notifyDataSetChanged();

    }

    /**
     * 加载信息模板
     */
    private void loadTemplate() {
        EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE, getString(R.string.templateNotReady), false);
        finish();
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_send) {
            String txt = editText.getText().toString().trim();
            Log.d("C_click", "msg send btn clicked with text " + txt);
            String msg = checkInputMsg(txt);
            if (S.isEmpty(msg)) {
                sendMessage(txt);
            } else {
                EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK, msg, false);
            }

        }

    }

    private void sendMessage(String txt) {
        String lastSendMessage = null;
        WorkingMsgUpRequest msgBean = null;
        if (S.isEmpty(extra_tgn)) {
            switch (extra_type) {
                case TYPE_NORMAL:
//                    lastSendMessage = MessageManager.getInstance().getGetWorkingPhraseInfo(txt, "10", null, null, null,
//                            selectedTemplateId);

                    msgBean = getGetWorkingPhraseInfo(txt, "10", null, null, null,
                            selectedTemplateId);

                    messageBean = cacheMessage(txt, "10", null, null, null, selectedTemplateId, extra_fln);
                    break;
                case TYPE_REMIND:
//                    lastSendMessage = MessageManager.getInstance().getRemindInfo(extra_tnb, extra_fke, extra_rdn, txt,
//                            selectedTemplateId);


                    msgBean = getRemindInfo(extra_tnb, extra_fke, extra_rdn, txt,
                            selectedTemplateId);

                    messageBean = cacheRemindMessage(extra_tnb, extra_fke, extra_rdn, txt, selectedTemplateId, extra_fln);
                    break;
                case TYPE_TASK:
//                    lastSendMessage = MessageManager.getInstance().getGetWorkingPhraseInfo(txt, "02", extra_tnb, extra_fke,
//                            null, selectedTemplateId);

                    msgBean = getGetWorkingPhraseInfo(txt, "02", extra_tnb, extra_fke,
                            null, selectedTemplateId);


                    messageBean = cacheMessage(txt, "02", extra_tnb, extra_fke, null, selectedTemplateId, extra_fln);
                    break;

            }
        } else {
            String txtContent = txt + getString(R.string.MSA_1) + extra_txt + "]";
//            lastSendMessage = MessageManager.getInstance().getGetWorkingPhraseInfo(txtContent, "99", extra_tnb,
//                    extra_fke, extra_tgn, selectedTemplateId);

            msgBean = getGetWorkingPhraseInfo(txtContent, "99", extra_tnb,
                    extra_fke, extra_tgn, selectedTemplateId);

            messageBean = cacheMessage(txtContent, "99", extra_tnb, extra_fke, extra_tgn, selectedTemplateId ,extra_fln);
        }
//        if (S.isNotEmpty(lastSendMessage)) {
//            ServiceManage.getInstance().sendMessage(lastSendMessage, progressBar, new MessageSendSuccessListener() {
//
//                @Override
//                public void onSuccess() {
//                    if (messageBean != null) {
//                        saveMessageTosqlite(messageBean);
//                    }
//                }
//            });
//            Log.d("C_msg", "invoke method ServiceManage.sentMessage success. args:" + lastSendMessage);
//        } else {
//            Log.w("C_msg", "last message is empty");
//        }

        if (msgBean != null) {
            this.progressBar.setVisibility(View.VISIBLE);
            Request<WorkingMsgUpResponse> request = null;
            try {
                request = new GsonRequest<WorkingMsgUpResponse>(RestfulUri.getUri(MessageModel.GWSM), WorkingMsgUpResponse.class, DataManager.getInstance().getMapper().writeValueAsString(msgBean), this.successListener, this.errorListener);
            } catch (IOException e) {
                e.printStackTrace();
                return;
            }
            requestQueue.add(request);
        }

    }

    private WorkingMsgUpRequest getRemindInfo(String extra_tnb, String extra_fke, String extra_rdn, String txt, String selectedTemplateId) {
        WorkingMsgUpRequest msgBean = getBaseMessageBean();

        //@TODO
        //msgBean.setstm();
        msgBean.setEnb(JavaBeanManager.getInstance().getUserinfo().getEnb());
        msgBean.setTnb(extra_tnb);
        msgBean.setFke(extra_fke);
        msgBean.setMid(selectedTemplateId);
        msgBean.setMti("03");
        //@TODO
        //msgBean.setrdn();
        msgBean.setTst("S");
        msgBean.setTxt(txt);
        return msgBean;
    }

    private WorkingMsgUpRequest getBaseMessageBean() {
        WorkingMsgUpRequest request = new WorkingMsgUpRequest();
        request.setHeader(SecurityUtil.getCommonRequestHeaderObject("GWSM"));
        request.setMt(MessageModel.GWSM);
        return request;
    }

    private WorkingMsgUpRequest getGetWorkingPhraseInfo(String txt, String type, String tnb,
                                                        String fke, String tgn, String mid) {
        WorkingMsgUpRequest msgBean = getBaseMessageBean();

        msgBean.setTxt(txt);
        msgBean.setMti(type);
        msgBean.setMid(mid);

        if (S.isNotEmpty(tnb)) {
            msgBean.setTnb(tnb);
        }

        if (S.isNotEmpty(fke)) {
            msgBean.setFke(fke);
        }
        //add by huzedong
        if (S.isNotEmpty(tgn)) {
            msgBean.setTgn(tgn);
        }
        return msgBean;
    }

    /**
     * 将短语保存到数据库
     *
     * @param messageBean
     */
    private void saveMessageTosqlite(MyMessageBean messageBean) {
        myMessageDBHelper.insert(messageBean);
    }

    /**
     * 缓存最近一条发送的短语
     *
     * @param txt
     * @param type
     * @param tnb
     * @param fke
     * @param tgn
     * @param mid
     * @return
     */
    private MyMessageBean cacheMessage(String txt, String type, String tnb, String fke, String tgn, String mid,String fln) {
        MyMessageBean bean = new MyMessageBean();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
        bean.setSTM(dateFormat.format(new Date()));
        bean.setMTI(type);
        bean.setTXT(txt);
        bean.setMID(mid);
        bean.setTNB(tnb);
        bean.setFKE(fke);
        bean.setFLN(fln);
        bean.setTGN(tgn);

        return bean;
    }

    /**
     * 缓存最近一条发送的催办信息
     *
     * @param tnb
     * @param fke
     * @param rdn
     * @param txt
     * @param mid
     * @return
     */
    private MyMessageBean cacheRemindMessage(String tnb, String fke, String rdn, String txt, String mid, String fln) {
        MyMessageBean bean = new MyMessageBean();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
        bean.setSTM(dateFormat.format(new Date()));
        bean.setTNB(tnb);
        bean.setFKE(fke);
        bean.setMID(mid);
        bean.setMTI("03");
        bean.setRDN(rdn);
        bean.setTST("S");
        bean.setFLN(fln);
        bean.setTXT(txt);
        return bean;
    }

    private String checkInputMsg(String txt) {
        String msg = null;
        if (S.isEmpty(txt)) {
            msg = getString(R.string.writeNull);
        } else if (txt.contains("@") || txt.contains("#")) {
            msg = getString(R.string.writeError);
        }
        return msg;
    }

    @Override
    public void setTitle(CharSequence title) {
        this.title.setText(title);
        super.setTitle(title);
    }

    @Override
    public void setTitle(int titleId) {
        this.setTitle(getString(titleId));
    }

    @SuppressLint("InflateParams")
    private void initactionBar() {
        final Activity context = this;

        ActionBar actionBar = getActionBar();

        actionBar.setCustomView(LayoutInflater.from(this).inflate(R.layout.actionbar_back_and_home, null));
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        actionBar.setDisplayShowCustomEnabled(true);

        this.title = (TextView) findViewById(R.id.txt_title);

        ImageView back = (ImageView) findViewById(R.id.action_back);
        back.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                finish();
            }
        });

        ImageView home = (ImageView) findViewById(R.id.action_home);
        home.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        });
    }

}
